const express = require('express');
const router = express.Router();
const pool = require('./db');
const fs = require('fs'); // 导入 fs 模块
const path = require('path'); // 导入 path 模块
// 检查章节编号是否已存在
router.get('/check-chapter-code', async (req, res) => {
    const { chapterId } = req.query;
    try {
        const [rows] = await pool.execute('SELECT * FROM chapters WHERE chapter_id =?', [chapterId]);
        res.json({ exists: rows.length > 0 });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});
// 检查章节标题是否已存在
router.get('/check-chapter-title', async (req, res) => {
    const { courseCode, chapterTitle } = req.query;
    try {
        const [rows] = await pool.execute('SELECT * FROM chapters WHERE course_code =? AND chapter_title =?', [courseCode, chapterTitle]);
        res.json({ exists: rows.length > 0 });
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});
// 新增章节接口
router.post('/add-chapter', async (req, res) => {
    const { chapter_id, chapter_title, chapter_content, course_code, chapter_order } = req.body;
    try {
        // 开始事务
        await pool.query('START TRANSACTION');
        
        // 更新现有章节的order
        await pool.execute(
            'UPDATE chapters SET chapter_order = chapter_order + 1 WHERE course_code = ? AND chapter_order >= ?',
            [course_code, chapter_order]
        );
        
        // 插入新章节
        await pool.execute(
            'INSERT INTO chapters (chapter_id, chapter_title, chapter_content, course_code, chapter_order) VALUES (?, ?, ?, ?, ?)',
            [chapter_id, chapter_title, chapter_content, course_code, chapter_order]
        );
        
        // 提交事务
        await pool.query('COMMIT');
        res.json({ message: '章节新增成功' });
    } catch (error) {
        // 回滚事务
        await pool.query('ROLLBACK');
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 删除章节接口
router.delete('/delete-chapter', async (req, res) => {
    const { chapterId } = req.query;
    try {
        // 开始事务
        await pool.query('START TRANSACTION');
        
        // 获取要删除的章节信息
        const [rows] = await pool.execute('SELECT * FROM chapters WHERE chapter_id = ?', [chapterId]);
        if (rows.length === 0) {
            res.json({ message: '章节不存在' });
            return;
        }
        
        const chapter = rows[0];
        
        // 查询该章节对应的资源
        const [resourceRows] = await pool.execute('SELECT * FROM resources WHERE belong_chapter = ?', [chapterId]);
        
        // 删除uploads目录下的文件
        resourceRows.forEach(row => {
            const resourcePath = row.resource_content;
            fs.unlinkSync(path.join(__dirname, '..', resourcePath));
        });
        
        // 删除resources表中的记录
        await pool.execute('DELETE FROM resources WHERE belong_chapter = ?', [chapterId]);
        
        // 根据被删除的资源的resource_id字段，删除learned_resources表中的记录
        if (resourceRows.length > 0) {
            // 提取所有资源ID
            const resourceIds = resourceRows.map(row => row.resource_id);
            // 批量删除学习记录
            await pool.execute(
                'DELETE FROM learned_resources WHERE resource_id IN (?)', 
                [resourceIds]
            );
        }
        
        // 删除章节记录
        await pool.execute('DELETE FROM chapters WHERE chapter_id = ?', [chapterId]);
        
        // 更新剩余章节的order
        await pool.execute(
            'UPDATE chapters SET chapter_order = chapter_order - 1 WHERE course_code = ? AND chapter_order > ?',
            [chapter.course_code, chapter.chapter_order]
        );
        
        // 提交事务
        await pool.query('COMMIT');
        res.json({ message: '删除成功' });
    } catch (error) {
        // 回滚事务
        await pool.query('ROLLBACK');
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});

// 获取课程章节接口
router.get('/get-chapters', async (req, res) => {
    const { courseCode } = req.query;
    try {
        const [rows] = await pool.execute('SELECT * FROM chapters WHERE course_code =? ORDER BY chapter_order ASC', [courseCode]);
        res.json(rows);
    } catch (error) {
        console.error(error);
        res.status(500).json({ message: '服务器错误' });
    }
});
module.exports = router;